package com.haiertvbic.umwcloudpop;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FilenameFilter;
import java.io.IOException;
import java.util.Calendar;
import java.util.Date;

import android.app.Activity;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.graphics.drawable.BitmapDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Looper;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Window;
import android.widget.ImageView;
import android.widget.Toast;

import com.haiertvbic.umwcloudpop.utils.SwitchLog;

public class UMWCloudPOP extends Activity {

	private final String savePath = "/data/data/com.haiertvbic.umwcloudpop/newpop";
	private final String uPath = "/mnt/usb";
	private final String exPath = "/umw-cloudpop";
	private final String exDiPath = "/defaultpop.png";
	private final String exNiPath = "/pop.png";
	private String[] pathLibray;
	private String[] dynPath;
	private String[] fileNames;
	private String[] copyFileNames;
	private int pathCount;
	private File saveDir;
	private ImageView pop;
	private FileInputStream fileInput;
	private FileOutputStream fileOutput;
	private BufferedReader readVaild;
	private String accessUPath;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.main);
		pop = (ImageView) findViewById(R.id.pop);

		createLocalDir();
		createDynPath();

	}
	
	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
	}

	@Override
	protected void onRestart() {
		// TODO Auto-generated method stub
		super.onRestart();
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		scanUsbStorage();
		new ReadTask().execute();
	}

	@Override
	protected void onStart() {
		// TODO Auto-generated method stub
		super.onStart();
	}

	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		super.onStop();
	}
	
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
	}



	private class ReadTask extends AsyncTask<Void, Void, Void>{

		@Override
		protected Void doInBackground(Void... params) {
			readUsbToLocal();
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			super.onPostExecute(result);
			pop();
		}
		
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if(keyCode == KeyEvent.KEYCODE_BACK){
			finish();
		}
		return super.onKeyDown(keyCode, event);
	}

	private void createLocalDir() {
		saveDir = new File(savePath);
		if (!saveDir.exists()) {
			boolean b = saveDir.mkdir();
			SwitchLog.v("lfav", "创建成功了吗 = " + b);
		} else {
			SwitchLog.v("lfav", "已经存在");
		}
	}

	private void createDynPath() {
		dynPath = new String[] { "a", "b", "c", "d", "e", "f", "g", "h", "i",
				"j", "k", "l", "m", "n", "o", "p", "q", "r" };
		pathCount = dynPath.length;
		pathLibray = new String[pathCount];
	}

	private void scanUsbStorage() {
		boolean oneU = false;
		for (int i = 0; i < pathCount; i++) {
			for(int j = 0; j < 10; j++){
				pathLibray[i] = uPath + "/sd" + dynPath[i] + j;
				File uDir = new File(pathLibray[i]);
				if (uDir.exists()) { // u盘存在
					File hasCerDir = new File(pathLibray[i] + exPath); // U盘中是否存在umw-cloudpop文件夹
					if (hasCerDir.exists()) { // umw-digpop文件夹存在
						fileNames = hasCerDir.list();
						accessUPath = pathLibray[i];
						oneU = true;
						break;
					} else { // umw-digpop文件夹不存在
						if (i == pathCount - 1 && j == 9) // 遍历完后在提示
							Toast.makeText(this, "没有检测到所需的文件", 1).show();
					}
				} else { // u盘不存在
					if (i == pathCount - 1 && j == 9) {
						Toast.makeText(this, "没有检测到U盘", 1).show(); // 遍历完后在提示
						localPop();
					}
				}
			}
			if(oneU)
				break;
		}
	}

	private void readUsbToLocal() {
		SwitchLog.v("lfav", "readUsbToLocal()");
		if (fileNames != null && fileNames.length != 0) { // 判断u盘指定目录中是否有文件
			for (int i = 0; i < fileNames.length; i++) {
				File accessFile = new File(accessUPath + exPath + "/"
						+ fileNames[i]);
				try {
					fileInput = new FileInputStream(accessFile);
					fileOutput = new FileOutputStream(savePath + "/"
							+ fileNames[i]);
					byte[] buffer = new byte[1024];
					int length = 0;
					while ((length = fileInput.read(buffer)) != -1) {
						fileOutput.write(buffer, 0, length);
					}
				} catch (FileNotFoundException e) {
					Looper.prepare();
					Toast.makeText(this, "没有找到相关文件", 1).show();
					Looper.loop();
					Looper.myLooper().quit();
				} catch (IOException e) {
					Looper.prepare();
					Toast.makeText(this, "文件复制失败", 1).show();
					Looper.loop();
					Looper.myLooper().quit();
				} finally {
					try {
						if (fileInput != null && fileOutput != null) {
							fileInput.close();
							fileOutput.close();
						}
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
		}
	}

	private boolean examine() {

		File savedFile = new File(savePath);
		copyFileNames = savedFile.list();
		if (copyFileNames.length != 0) {
			return true;
		}
		return false;
	}

	private boolean readValid() {

		SwitchLog.v("lfav", "readValid()");
		if (examine()) {
			SwitchLog.v("lfav", "copyFileNames.length = "
					+ copyFileNames.length);
			for (int i = 0; i < copyFileNames.length; i++) {
				SwitchLog.v("lfav", "copyFileName = " + copyFileNames[i]);
				if (copyFileNames[i].endsWith(".txt")) {
					SwitchLog.v("lfav", "vaild = " + copyFileNames[i]);
					try {
						readVaild = new BufferedReader(new FileReader(savePath
								+ "/" + copyFileNames[i]));
						String date = "";
						String s = "";
						while ((s = readVaild.readLine()) != null) {
							date = date + s;
						}
						SwitchLog.v("lfav", "date = " + date);
						String[] dates = date.split("-");
						SwitchLog.v("lfav", "dates len = " + dates.length);
						SwitchLog.v("lfav", "valYear = " + dates[0]);
						SwitchLog.v("lfav", "valMonth = " + dates[1]);
						SwitchLog.v("lfav", "valDay = " + dates[2]);
						if (dates.length == 3) {
							Date validDate = new Date(
									Integer.valueOf(dates[0]),
									Integer.valueOf(dates[1]),
									Integer.valueOf(dates[2]));
							Calendar calendar = Calendar.getInstance();
							int year = calendar.get(Calendar.YEAR);
							SwitchLog.v("lfav", "curYear = " + year);
							int month = calendar.get(Calendar.MONTH) + 1;
							SwitchLog.v("lfav", "curMonth = " + month);
							int day = calendar.get(Calendar.DAY_OF_MONTH);
							SwitchLog.v("lfav", "curDay = " + day);
							Date currentDate = new Date(year, month, day);
							boolean canPOP = currentDate.before(validDate);// true可pop
							SwitchLog.v("lfav", "before = " + canPOP);
							return canPOP;
						} else {
							Toast.makeText(this, "时间格式不对", 1).show();
							return true;
						}
					} catch (FileNotFoundException e) {
						e.printStackTrace();
					} catch (IOException e) {
						e.printStackTrace();
					} finally {
						if (readVaild != null) {
							try {
								readVaild.close();
							} catch (IOException e) {
								e.printStackTrace();
							}
						}
					}
					break;
				}
			}
		}
		return false;
	}

	private void localPop() {
		if (saveDir.exists()) {

			String[] pngNames = saveDir.list(new FilenameFilter() {

				@Override
				public boolean accept(File dir, String filename) {
					return filename.endsWith(".png");
				}
			});
			SwitchLog.v("lfav", "png len = " + pngNames.length);
			if (pngNames.length != 0) {
				SwitchLog.v("lfav", "local-if-pngNames.length = " + pngNames.length);
				BitmapDrawable bitmap = new BitmapDrawable(savePath + exDiPath);
				pop.setImageDrawable(bitmap);
			} else {
				SwitchLog.v("lfav", "local-else");
//				Builder builder = new Builder(this);
//				builder.create();
//				builder.setTitle("没有图片可显示");
//				builder.setMessage("请插入U盘后点击确定");
//				builder.setPositiveButton("确定", new OnClickListener() {
//
//					@Override
//					public void onClick(DialogInterface dialog, int which) {
//						scanUsbStorage();
//						new ReadTask().execute();
//					}
//				});
//				builder.show();
				Toast.makeText(this, "没有图片可显示,请插入U盘", 1).show();
			}
		}
	}

	private void pop() {
		SwitchLog.v("lfav", "pop()");
		if (readValid()) {
			BitmapDrawable bitmap = new BitmapDrawable(savePath + exNiPath);
			pop.setImageDrawable(bitmap);
		} else {
			BitmapDrawable bitmap = new BitmapDrawable(savePath + exDiPath);
			pop.setImageDrawable(bitmap);
		}
	}

}